﻿using Entity.BaseEntitys;
using Entity.Enum;
using EntityFrameWorkCore;
using Repository.RepositoryExtension;
using ShardingCore.Extensions.ShardingPageExtensions;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Utility.Helper;

namespace Repository.Repository
{

    public static class RepositoryExtension
    {

        public static async ValueTask<ShardingPagedResult<TEntity>>  QaPagedResult<TEntity, TPagedResult>(this IQueryable<TEntity> Queryable, TPagedResult PageResult) where TPagedResult: IPageResult
        {
            var totalCount = Queryable.Count();//总数
  
                if (!PageResult.Sorting.IsNullOrWhiteSpace())
                    Queryable = Queryable.OrderByField(PageResult.Sorting, PageResult.OrderByDescending);

            return await Queryable.ToShardingPageAsync(PageResult.PageIndex, PageResult.PageSize);//分页
        }

  
        public static async ValueTask<ShardingPagedResult<TEntity>> EaPagedResult<TEntity, TPagedResult>(this IEnumerable<TEntity> Enumerable, TPagedResult PageResult) where TPagedResult : IPageResult
            => await Enumerable.AsQueryable().QaPagedResult(PageResult);
   

  
        public static void SaveChanges<TEntity, TPrimaryKey, TDbContext>(this IRepository<TEntity, TPrimaryKey, TDbContext> Repository) where TEntity : class, IEntity<TPrimaryKey> where TDbContext : BaseDbContext<TDbContext>
        {
            var obj = Repository as Repository<TEntity, TPrimaryKey, TDbContext>;
                obj.GetDbContext().SaveChanges(true);
        }

   
        public static async Task SaveChangesAsync<TEntity, TPrimaryKey, TDbContext>(this IRepository<TEntity, TPrimaryKey, TDbContext> Repository) where TEntity : class, IEntity<TPrimaryKey> where TDbContext : BaseDbContext<TDbContext>
        {
            var obj = Repository as Repository<TEntity, TPrimaryKey, TDbContext>;
            await obj.GetDbContext().SaveChangesAsync(true);
        }
    }
}
